<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/9/17
 * Time: 11:34
 */

namespace app\wap\controller;

use think\Controller;
use think\Db;

class Article extends Controller
{

    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
    }

    //文章查询
    public function index(){
        $post=  request()->request();
        $where='';
        $where['a.status']=1;
        $where['a.is_show']='0';
        $wheres['status']=1;
        $wheres['is_show']='0';
        if (!empty($post['class_id'])){
            $where['a.article_cate_id']=$post['class_id'];
            $wheres['article_cate_id']=$post['class_id'];
        }
        if (!empty($post['search'])){
            $where['a.tag|a.title']=['like','%'.$post['search'].'%'];
            $wheres['tag|title']=['like','%'.$post['search'].'%'];
        }
        $city_where = "";
        if (!empty($post['city_id'])){
            //是否是国家级别
            $city = db("city")->where(['id'=>$post['city_id']])->find();
            if($city['groupid']==0){
                $city_ids = db("city")->field("id")->where(['groupid'=>$post['city_id'],'show'=>1,'deleted'=>0])->select();
                $city_where_list = [];
                if(!empty($city_ids)){
                    foreach($city_ids as $value){
                        $city_where_list[] = 'FIND_IN_SET('.$value['id'].',city_id)';
                    }
                }
                $city_where_list[] = 'city_id=999999';
                if($post['city_id']=='48'){//美国
                    $city_where_list[] = 'city_id=8888';
                }elseif($post['city_id']=='51'){//加拿大
                    $city_where_list[] = 'city_id=7777';
                }
                $city_where = implode(" or ",$city_where_list);
            }else{
                $city_where = 'FIND_IN_SET('.$post['city_id'].',city_id) or city_id=999999';
                if($city['groupid']=='48'){
                    $city_where .= " or city_id=8888";
                }elseif($city['groupid']=='51'){
                    $city_where .= " or city_id=7777";
                }
            }
        }

        //页码
        $pagenum=!empty($post['pagenum'])?$post['pagenum']:1;
        //每页显示数量
        $pagelimit=!empty($post['pagelimit'])?$post['pagelimit']:10;
        $pagecount= db('article')->where($wheres)->where($city_where)->count();
        $totalpage=ceil($pagecount/$pagelimit);
        if ($pagenum==1){
            $pages=0;
        }else{
            $pages= ($pagenum-1)*$pagelimit;
        }

        $article= db('article')
            ->alias('a')
            ->join('attachment c' ,'a.thumb=c.id');
        $article=  $article->where($where)->where($city_where);
        $article= $article->field('a.id as article_id,a.title,a.create_time,a.fabulous,a.browse,c.filepath as img,video,a.is_top,a.sort_num')
            ->order('a.is_top desc,a.sort_num desc,a.update_time desc')
            ->limit($pages,$pagelimit)
            ->select();

        if (!empty($article)) {
            foreach ($article as $k => $v) {
                //start 20210330 修改缩略图之后 启用filepath
                $article[$k]['img'] = $this->replaceArticleThumbImg($v['img']);
                //end 20210330
                $article[$k]['create_time'] = date('Y-m-d',$v['create_time']);
                $article[$k]['fabulous']= db('fabulous')->where('article_id',$v['article_id'])->count();
                $article[$k]['comment_num']= db('article_comment')->where('article_id',$v['article_id'])->count();
                if (!empty($v['video'])){
                    $d=db('attachment')->where('id',$v['video'])->field('filepath')->find();
                    $article[$k]['video'] =$d['filepath'];
                }
            }

            return json_encode(['code'=>0,'msg'=>'ok','data'=>[
                'pagenum'=>$pagenum,//页码
                'pagecount'=>$pagecount,//总数居
                'totalpage'=>$totalpage,//总页数
                'pagelimit'=>$pagelimit,//总页数
                'data'=>$article,
            ]]);
        }else{
            return json_encode(['code'=>0,'msg'=>'您期待的攻略有待开发呦~','data'=>'']);
        }
    }

    public function insertSort($arr,$c) {
        $len=count($arr['goods']);
        if ($c=='1'){
            for($i=1; $i<$len; $i++ ) {
                $tmp = $arr['goods'][$i]['jiage'];;
                $dmp = explode('~',$tmp);
                if (!empty($dmp[1])){

                    $dmp=floor($dmp[1]);
                }else{
                    $dmp=floor($dmp[0]);
                }
                //内层循环控制，比较并插入
                for($j=$i-1;$j>=0;$j--) {
                    $tmp1 = $arr['goods'][$j]['jiage'];
                    $dmp1 =   explode('~',$tmp1);
                    if (!empty($dmp1[1])){
                        $dmp1=floor($dmp1[1]);
                    }else{
                        $dmp1=floor($dmp1[0]);
                    }
                    if((int)$dmp < (int)$dmp1) {
                        $tm= $arr['goods'][$j+1];
                        //发现插入的元素要小，交换位置，将后边的元素与前面的元素互换
                        $arr['goods'][$j+1] = $arr['goods'][$j];
                        $arr['goods'][$j] = $tm;
                    }
                }
            }
            return $arr;
        }
    }

    //分类查询
    public function frticleclass(){
        $da= db('article_cate')->field('id,name')->select();
        return json_encode(['code'=>0,'msg'=>'ok','data'=>$da]);
    }

    //文章点赞
    public function fabulous(){
        $post=request()->request();
        if (!empty($post)){
            $d=  db('fabulous')->where('member_id',$post['member_id'])->where('article_id',$post['article_id'])->find();
            if (empty($d)){
                $da=  db('fabulous')->insert([
                        'member_id'=>$post['member_id'],
                        'article_id'=>$post['article_id'],
                        'creationtime'=>time(),
                    ]
                );
                if ($da==true){
                    return json_encode(['code'=>0,'msg'=>'点赞成功']);
                }else{
                    return json_encode(['code'=>101,'msg'=>'点赞失败']);
                }
            }else{
                $da=  db('fabulous')->where('member_id',$post['member_id'])->where('article_id',$post['article_id'])->delete();
                if ($da){
                    return json_encode(['code'=>0,'msg'=>'取消点赞']);
                }else{
                    return json_encode(['code'=>101,'msg'=>'取消失败']);
                }
            }
        }
    }

    //文章搜索
    public function  search(){
        $search=request()->request('search');
        if ($search){
            $map['tag']=['like','%'.$search.'%'];
            $article=  db('article')
                ->where($map)
                ->field('id,title')
                ->limit(20)
                ->select();
            if ($article){
                return json_encode(['code'=>0,'msg'=>'ok','data'=>$article]);
            }else{
                return json_encode(['code'=>101,'msg'=>'查询失败']);
            }
        }else{
            return json_encode(['code'=>101,'msg'=>'参数为空查询失败']);
        }
    }

    //文章详情
    public function details(){
        $post= request()->request();
        if (!empty($post['article_id'])){
            db('article')->where('id',$post['article_id'])->setInc('browse');
            $da= db('article')
                ->alias('a')
                ->where('a.id',$post['article_id'])
                ->join('article_cate b' ,'a.article_cate_id=b.id')
                ->join('attachment c' ,'a.thumb=c.id')
                ->field('a.id as article_id,a.title,a.tag,a.description,a.content,a.create_time,a.browse ,
                    b.name as class_name,b.id as class_id,c.filepath as img,a.video,a.share_img,a.city_id')
                ->find();
            if (!empty($da['video'])){
                $d=db('attachment')->where('id',$da['video'])->field('filepath')->find();
                $da['video'] =$d['filepath'];
                //判断是否已经存在处理过的图片
                if (empty($da['share_img'])){
                    if(substr($da['img'],0,4)=='http'){
                        $path = $this->images($da['img']);//处理图片
                    }else{
                        $path = $this->images('.'.$da['img']);//处理图片
                    }

                    if (!$path){
                        $path = $da['img'];
                    }else{
                        db('article')->where('id',$post['article_id'])->update([
                            'share_img' => $path
                        ]);
                    }
                    $da['share_img'] = $path;//视频分享封面图片
                }
            }else{
                $da['video']='';
            }

            $da['dianzan']=0;
            if (!empty($post['member_id'])){
                $ds=  db('fabulous')->where('member_id',$post['member_id'])->where('article_id',$post['article_id'])->find();
                if (!empty($ds)){
                    $da['dianzan']=1;
                }else{
                    $da['dianzan']=0;
                }
            }

            $da['tag']= str_replace('，',',',$da['tag']);
            $da['tag']= !empty($da['tag'])?explode(',',$da['tag']):'';
            $da['create_time']= date('Y-m-d',$da['create_time']);
            $da['fabulous'] =db('fabulous')->where('article_id',$da['article_id'])->count();
            $da['comment_conut']=db('article_comment')->where('article_id',$da['article_id'])->count();
            $da['comment']=db('article_comment')
                ->alias('a')
                ->where('a.article_id',$da['article_id'])
                ->join('member b','a.member_id=b.member_id')
                ->join('attachment c','b.thumb=c.id')
                ->field('a.content,a.creattime,a.comment_img,b.member_nickname,c.filepath as touxiang')
                ->limit(0,3)->select();
            if (!empty( $da['comment'])){
                foreach ($da['comment'] as $s=>$g) {
                    $da['comment'][$s]['creattime']= date('Y-m-d H:i:s', $g['creattime']);
                }
            }

            //城市名称
            $city_name = '';
            if (!empty($post['city_id']) && $post['city_id']>0){
                $city = db("city")->where("id",$post['city_id'])->find();
                $city_name = $city['name'];
            }else{
                if(!empty($da['city_id'])){
                    if($da['city_id']=='999999'){//全部
                        $city = db("city")->where("deleted",0)->where("show",1)->find();
                        $city_name = $city['name'];
                    }elseif($da['city_id']=='8888'){//美国
                        $city = db("city")->where("groupid",48)->where("deleted",0)->where("show",1)->find();
                        $city_name = $city['name'];
                    }elseif($da['city_id']=='7777'){//加拿大
                        $city = db("city")->where("groupid",51)->where("deleted",0)->where("show",1)->find();
                        $city_name = $city['name'];
                    }else{
                        $cityArr = explode(",",$da['city_id']);
                        $cityArr = array_filter($cityArr);
                        if(!empty($cityArr)){
                            $city_id = array_shift($cityArr);
                            $city = db("city")->where("id",$city_id)->find();
                            $city_name = $city['name'];
                        }
                    }
                }
            }

            $da['city_name'] = $city_name;

            return json_encode(['code'=>0,'msg'=>'ok','data'=>$da]);
        }
    }

    public function comment(){
        $da= request()->request();
        if (!empty($da['article_id'])){
            $comment=db('article_comment')
                ->alias('a')
                ->where('a.article_id',$da['article_id'])
                ->join('member b','a.member_id=b.member_id')
                ->join('attachment c','b.thumb=c.id')
                ->field('a.content,a.creattime,a.comment_img,b.member_nickname,c.filepath as touxiang')
                ->order("a.creattime desc")
                ->select();
            if (!empty($comment)){
                foreach ($comment as $s=>$g) {
                    $comment[$s]['creattime']= date('Y-m-d H:i:s', $g['creattime']);
                    $comment[$s]['comment_img']= json_decode($g['comment_img']);
                }
            }
            return json_encode(['code'=>0,'msg'=>'ok','data'=>$comment]);
        }else{
            return json_encode(['code'=>101,'msg'=>'文章id错误','data'=>'']);
        }
    }

    //新增评论
    public function addcomment(){
        $da= request()->request();
        $shu=[];
        if(!empty($da)){
            // 启动事务
            Db::startTrans();
            try{
                db('article_comment')->insert([
                    'member_id'=>$da['member_id'],
                    'article_id'=>$da['article_id'],
                    'content'=>$da['content'],
                    'creattime'=>time(),
                    'comment_img'=>$da['comment_img'],
                ]);
                // 提交事务
                Db::commit();
                $shu=['code'=>0,'msg'=>'评价成功','data'=>''];
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $shu=['code'=>101,'msg'=>$e->getMessage(),'data'=>''];
            }
        }

        return json_encode($shu);
    }

    public function images($path_1=''){
        $path_2 = './77.gif';//按钮

        //创建图片对象
        $path   = '/uploads/admin/article_thumb/';
        $dir    = date('Ymd',time());
        if (!is_dir(".$path$dir")){
            mkdir(".$path$dir",0777);
        }
        $name1= md5($path_1).'.png';
        $name= md5($path_1).'.jpg';

        $z= explode('/',getimagesize($path_1)['mime'])[1];

        $imagecreatefrom='imagecreatefrom'.$z;
        $image_1 = $imagecreatefrom($path_1);
        $image_2 = imagecreatefromgif($path_2);
        $image_3 = imageCreatetruecolor(imagesx($image_1),imagesy($image_1));

        //为真彩画布创建白色背景
        $color = imagecolorallocate($image_3, 255, 255, 255);

        imagefill($image_3, 0, 0, $color);
        //设置透明
        imageColorTransparent($image_3, $color);
        //处理背景
        imagecopyresampled($image_3, $image_1, 0, 0, 0, 0, imagesx($image_1), imagesy($image_1), imagesx($image_1), imagesy($image_1));
        //与图片二合成
        imagecopymerge($image_3, $image_2, imagesx($image_1)/2-imagesx($image_2)/2, imagesy($image_1)/2-imagesy($image_2)/2,
            0, 0, imagesx($image_2), imagesy($image_2), 100);
        // 输出合成图片
        $png= imagejpeg($image_3,".$path$dir/".$name);

        if (!$png){
            return false;
        }
        return $path.$dir.'/'.$name;
    }


    //获取首页推荐攻略
    public function getHomeArticle(){
        $articleData = db("indexset")->where("id",3)->find();
        $err = 1;
        $data = [];
        if(!empty($articleData['id_str'])){
            $err = 0;
            $id_str = $articleData['id_str'];
            $id_arr = explode(",",$id_str);

            $idArr = [];
            foreach ($id_arr as $k=>$v) {
                $arr = explode("_",$v);
                $idArr[] = $arr[1];
            }

            $idArr = array_unique($idArr);

            if(!empty($idArr)){
                foreach ($idArr as $k=>$v) {
                    $article = db('article')
                        ->alias('a')
                        ->join('attachment c' ,'a.thumb=c.id')
                        ->where("a.id",$v)
                        ->field('a.id as article_id,a.title,a.create_time,a.fabulous,
                            a.browse,c.filepath as img,video,a.is_top')
                        ->find();

                    if (!empty($article)) {
                        //start 20210330 修改缩略图之后 启用filepath
                        $article['img'] = $this->replaceArticleThumbImg($article['img']);
                        //end 20210330
                        $article['create_time'] = date('Y-m-d', $article['create_time']);
                        $article['fabulous'] = db('fabulous')->where('article_id', $article['article_id'])->count();
                        $article['comment_num'] = db('article_comment')
                            ->where('article_id', $article['article_id'])->count();
                    }
                    $data[] = $article;
                }
            }else{
                $err = 1;
            }
        }

        if($err==0){
            $shu=[
                'code'=>0,
                'msg'=>'请求成功',
                'data'=>['data'=>$data]
            ];
        }else{
            $shu=[
            'code'=>101,
            'msg'=>'暂无更多数据',
            ];
        }

        return json_encode($shu);
    }

    //替换攻略图片地址 20210330
    protected function replaceArticleThumbImg($thumb)
    {
        return empty($thumb) ? '' :
            (strpos($thumb,'http')===false ?
                str_replace('\\','/',$thumb) : $thumb
            );
    }

}